#! /bin/zsh
# This pre-commit hook uses clang-format to format the staged changes.

if ! git rev-parse --verify HEAD >/dev/null 2>&1
then
	echo "not currently working in a git repository or unable to verify HEAD, therefore skipping `basename $0`"
	exit 0
fi

set -e

REPO_ROOT=$(git rev-parse --show-toplevel)
DIFF_ARGS="--name-only --diff-filter=ACMRT"
git diff-index ${=DIFF_ARGS} --cached HEAD | grep -E "\.(h|hpp|c|cpp|m|mm)$" | while read -r FILE
do
	FILE_PATH="${REPO_ROOT}"/"${FILE}"
	if [[ `git diff ${=DIFF_ARGS} "${FILE_PATH}"` == $FILE ]]
	then
		echo -e "\xF0\x9F\x94\xA5 \xE2\x98\xA0 \xF0\x9F\x94\xA5 WARNING: creating a stash for file due to unstaged changes: ${FILE}"
		# format before stashing to avoid a merge conflict when applying the stash after commit
		xcrun clang-format -i "${FILE_PATH}"
		git stash push -k -q -m "pre-clang-format: ${FILE}" -- "${FILE_PATH}"
    fi

	xcrun clang-format -i "${FILE_PATH}"
	git add "${FILE_PATH}"
done
